<?php
namespace app\http\middleware;

use EasyWeChat\Factory;
use think\facade\Session;

class WechatAuth
{
    const SNSAPI_USERINFO = 'userinfo';
    const SNSAPI_BASE = 'base';

    public function handle($request, \Closure $next, $options = '')
    {
        $params = explode(',', $options);
        $account = $params[0] ?? $params[0] ? : 'default';
        $scope = $params[1] ?? self::SNSAPI_BASE;
        if (! Session::has('wechat_user_'.$account)) {
            $config = config('wechat.'.$account);
            if ($config) {
                $wechat = Factory::officialAccount($config);

                if (! $wechat->oauth->getRequest()->get('code')) {
                    $wechat->oauth->scopes(['snsapi_' . $scope])->redirect($request->url(true))->send();
                } else {
                    Session::set('wechat_user_'.$account, $wechat->oauth->user()->getOriginal());
                }
            }
        }

        return $next($request);
    }
}
